<?php
App::uses('AppController', 'Controller');
App::uses('Sanitize', 'Utility');
/**
 * Versions Controller
 *
 * @property Version $Version
 */
class VersionsController extends AppController {

/**
*RLEB
*Definition d'un pagination a 25 appli/page + tri par defaut sur Application.name
*/
	/*public $paginate = array(
        'limit' => 25,
        'order' => array(
            'Version.name' => 'asc'
        )
    );*/


/**
*RLEB
*Helper 
*/
	public $helpers = array('Date', 'Datefr', 'Moninput', 'Session_gpp');



	function beforeFilter(){
		parent::beforeFilter();
		//$this->Auth->allow('index');
	}
/**
 * RLEB
 *
 *
 * @return void
 */
	public function VersionsOfApplication($id) {
		$id = Sanitize::paranoid($id);
		$this->myid=$id;
		$this->Version->recursive = -1;
		$data = $this->paginate('Version',array("Version.application_id"=>$id));
    	$sonapp = $this->Version->Application->find('first',array('conditions' => array('Application.id' => $id),'recursive'=>-1));

		foreach ($data as $version):
			//on compte le nombre de tables rattaché à la version et aux versions précédente
			//une table de la versions précédente est comptée si une table de même nom n'existe pas pour la version en cours
			//une table de la versions précédente est comptée si la version de fin est strictement supérieur
			$nbversion = $this->Version->Table->find('count', 
				array('fields' => 'Table.id', 
					'conditions' => array(
						"Table.version_id in (select ver.id
		            					from tables tab, versions ver
		                				where tab.version_id=ver.id
		            					and ver.application_id=".$sonapp['Application']['id']."
		                         		)",
		                 "not exists (select 1 
		            			from tables tab , versions ver
		            			where tab.version_id=ver.id
		 						and ver.application_id=1
		            			and tab.name=`table`.name
		            			and tab.version_id>`table`.version_id
		            			and tab.version_id<=".$version['Version']['id']."
		            			)",
						"(Table.version_id_fin = 0 or Table.version_id_fin > ".$id.")",
						"Table.version_id <= ".$id
					),'recursive'=>-1 
				)
			);
			$nbtables[$version['Version']['id']]=array("count"=>$nbversion);
		endforeach;

		if (isset($nbtables)){
			$this->set('nbtables',$nbtables);
		}
		$this->set('sonapp', $sonapp);
		$this->set('versions', $data);
		$this->render("index");
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$id = Sanitize::paranoid($id);
		$this->Version->id = $id;
		if (!$this->Version->exists()) {
			throw new NotFoundException(__('Invalid version'));
		}
		$laversion = $this->Version->find('first',array('conditions' => array('Version.id' => $id),'recursive'=>0));
		$sonapp = $this->Version->Application->find('first',array('conditions' => array('Application.id' => $laversion['Version']['application_id']),'recursive'=>-1));
		
		$lsttable= $this->Version->Table->find('all' ,
			array(
				'conditions' => array(
					"Table.version_id in (select ver.id
		            					from tables tab, versions ver
		                				where tab.version_id=ver.id
		            					and ver.application_id=".$sonapp['Application']['id']."
		                         		)",
		         	"not exists (select 1 
		            			from tables tab , versions ver
		            			where tab.version_id=ver.id
		 						and ver.application_id=1
		            			and tab.name=`table`.name
		            			and tab.version_id>`table`.version_id
		            			and tab.version_id<=".$id."
		            			)",
						"(Table.version_id_fin = 0 or Table.version_id_fin > ".$id.")",
						"Table.version_id <= ".$id
	         	),'recursive'=>-1));


		$this->set('sonapp', $sonapp);
		$this->set('lsttable', $lsttable);
		$this->set('version', $laversion);
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$id = Sanitize::paranoid($id);
		$this->Version->id = $id;
		if (!$this->Version->exists()) {
			throw new NotFoundException(__('Invalid version'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data=Sanitize::clean($this->request->data, array('encode' => false, 'unicode'=> true));
			if ($this->Version->save($this->request->data)) {
				$this->Session->setFlash(__('The version has been saved'),'default',array("class"=>'success'));
				$this->redirect(array('action' => 'view',$id));
			} else {
				$this->Session->setFlash(__('The version could not be saved. Please, try again.'),'default',array("class"=>'error'));
			}
		} else {
			$this->request->data = $this->Version->read(null, $id);
		}
		$this->set(compact('applications'));
	}

/**
 * add method
 *
 * @return void
 */
	public function add($idapplication) {
		$idapplication = Sanitize::paranoid($idapplication);
		if ($this->request->is('post')) {
			$this->request->data=Sanitize::clean($this->request->data, array('encode' => false, 'unicode'=> true));
			$this->Version->create();
			if ($this->Version->save($this->request->data)) {
				$this->Session->setFlash(__('The version has been saved'),'default',array("class"=>'success'));
				$this->redirect(array('controller'=>'applications','action' => 'view',$idapplication));
			} else {
				$this->Session->setFlash(__('The version could not be saved. Please, try again.'),'default',array("class"=>'error'));
			}
		}
		//$applications = $this->Version->Application->find('list');
		$this->set('idapplication',$idapplication);
		$this->set(compact('applications'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$id = Sanitize::paranoid($id);
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Version->id = $id;
		$lapplication = $this->Version->find('first',array('conditions' => array('Version.id' => $id),'recursive'=>-1));
		if (!$this->Version->exists()) {
			throw new NotFoundException(__('Invalid version'));
		}
		if ($this->Version->delete()) {
			$this->Session->setFlash(__('The version has been deleted'),'default',array("class"=>'success'));
			//$this->redirect(array('action' => 'VersionsOfApplication',$lapplication['Version']['application_id']));
			$this->redirect(array('controller'=>'applications','action' => 'view',$lapplication['Version']['application_id']));
		}
		$this->Session->setFlash(__('The version could not be deleted. Please, try again.'),'default',array("class"=>'error'));
		$this->redirect(array('controller'=>'applications','action' => 'view',$lapplication['Version']['application_id']));
	}

}